import sys
import os
from sklearn import svm
from sklearn.decomposition import PCA
import numpy as np

def read4txt(txt):
    '''
    将txt中的电路读成二维列表
    '''
    with open(txt,'r') as f:
        lines = f.readlines()
        num_l = 1
        matr = []
        for line in lines:
            l = line.split()
            if l[0]=='xor':
                tem = [0]*num_l
                tem[int(l[1])]=1
                tem[int(l[2])]=1
                matr.append(tem)
            elif l[0]=='and':
                tem = [0]*num_l
                tem[int(l[1])]=2
                tem[int(l[2])]=2
                matr.append(tem)
            elif l[0]=='ref':
                tem = [0]*num_l
                tem[int(l[1])]=3
                matr.append(tem)
            else:
                pass
            num_l+=1
    re=[]
    for m in matr:
        m+=[0]*(len(matr[-1])-len(m))
        re.append(m)
    re = [n for a in re for n in a]
    return len(re),re

def loaddataset(folder,result):
    filename=os.path.join(folder,result)
    labels=[]
    re=[]
    lns=[]
    with open(filename) as fl:
        lines = fl.readlines()
        for line in lines:
            path = line.split()
            if len(path)>4:
                label=1
            else:
                label=0
            labels.append(label)
            cirpath=os.path.join(folder,path[0])
            ln,ma=read4txt(cirpath)
            re.append(ma)
            lns.append(ln)
    for i in range(len(re)):
        re[i]=re[i]+[0]*(max(lns)-len(re[i]))
    return labels,re

arg1,arg2 = sys.argv[1],sys.argv[2]
labels,re=loaddataset(arg1,arg2)
label = np.asarray(labels)
data = np.asarray(re)

pca = PCA(n_components=3)
new_data = pca.fit_transform(data)
with open(f'{arg1}_pca.txt','w') as f:
    f.write('xcol ycol zcol color\n')
    for i in zip(new_data,label):
        x,y,z,color = i[0][0],i[0][1],i[0][2],i[1]
        f.write(f'{x:.5f} {y:.5f} {z:.5f} {color}\n')




if label.shape[0]==data.shape[0]:
    length = label.shape[0]
    test_n = length//10
data_train = data[:-test_n]
data_test = data[-test_n:]
label_train = label[:-test_n]
label_test = label[-test_n:]


clf = svm.SVC(gamma='scale')
clf.fit(data_train,label_train)

n = 0
path = f'{arg1}_{arg2}_result.txt'
import time
s_time = time.time()
for i in range(label_test.shape[0]):
    test = data_test[i].reshape(1,-1)
    cate_pre = clf.predict(test)
    if cate_pre[0]==label_test[i]:
        n+=1
e_time = time.time()       
cost = e_time-s_time
result = f'准确分类个数:{n}\n总样本数{label_test.shape[0]}\n准确率:{n/label_test.shape[0]}\n平均每个样本用时:{cost/n}'
with open(path,'w') as f:
    f.write(result)
